package com.smit.livevideo.sample.fragment;

import java.io.InputStream;
import java.util.ArrayList;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;

import com.smit.livevideo.R;
import com.smit.utils.LogUtil;

/**
 * Created by smfang on 2015/11/24.
 * 进度条绘图UI
 */
public class LineProgressBar extends View implements Handler.Callback
{
    /**
     * 是否显示中间的进度
     */
    private static final int REFRESH_POINT_PIC = 10;
    /**
     * 画笔对象的引用
     */
    private static final String TAG = LineProgressBar.class.getSimpleName();
    private Paint paint;
    private Bitmap point;
    private ArrayList<Bitmap> pointBitmaps;
    /**
     * 圆环的颜色
     */
    private int roundColor;

    /**
     * 圆环进度的颜色
     */
    private int roundProgressColor;

    /**
     * 中间进度百分比的字符串的颜色
     */
    private int textColor;

    /**
     * 中间进度百分比的字符串的字体
     */
    private float textSize;

    /**
     * 圆环的宽度
     */
    private float roundWidth;

    /**
     * 最大进度
     */
    private int max;

    /**
     * 当前进度
     */
    private int progress;

    private int pictures[]
            = {R.drawable.search_progress_point_anim_01, R.drawable.search_progress_point_anim_02,
            R.drawable.search_progress_point_anim_03, R.drawable.search_progress_point_anim_04,
            R.drawable.search_progress_point_anim_05, R.drawable.search_progress_point_anim_06,
            R.drawable.search_progress_point_anim_07, R.drawable.search_progress_point_anim_08,
            R.drawable.search_progress_point_anim_09 };

    private int picNum = 0;
    private Handler handler;
    private float mRectfbarLeft;
    private float mRectfbarTop;
    private float mRectfbarRight;
    private float mRectfbarBottom;
    private float mRectfbarProgressWidth;
    private float mRectfbarProgressPointwidth;
    private float mRoundCornerRadius;

    /**
     * LineProgressBar 构造函数
     * @param context context参数
     */
    public LineProgressBar(Context context)
    {
        this(context, null);
    }

    /**
     * LineProgressBar 构造函数
     * @param context context参数
     * @param attrs 参数
     */
    public LineProgressBar(Context context, AttributeSet attrs)
    {
        this(context, attrs, 0);
    }

    /**
     * LineProgressBar 构造函数
     * @param context context参数
     * @param attrs 参数
     * @param defStyle 参数
     */
    public LineProgressBar(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        handler = new Handler(this);
        initPointPicture();

        Resources res = getResources();
        point = pointBitmaps.get(0);
        paint = new Paint();
        TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.LineProgressBar);

        //获取自定义属性和默认值
        roundColor = mTypedArray.getColor(R.styleable.LineProgressBar_roundColor, Color.RED);
        roundProgressColor = mTypedArray.getColor(R.styleable.LineProgressBar_roundProgressColor, Color.GREEN);
        roundWidth = mTypedArray.getDimension(R.styleable.LineProgressBar_roundWidth, 4);
        max = mTypedArray.getInteger(R.styleable.LineProgressBar_max, 100);

        mRectfbarLeft = mTypedArray.getDimension(R.styleable.LineProgressBar_rectfbarLeft,
                res.getDimension(R.dimen.px40));
        mRectfbarTop = mTypedArray.getDimension(R.styleable.LineProgressBar_rectfbarTop,
                res.getDimension(R.dimen.px38));
        mRectfbarRight = mTypedArray.getDimension(R.styleable.LineProgressBar_rectfbarRight,
                res.getDimension(R.dimen.px840));
        mRectfbarBottom = mTypedArray.getDimension(R.styleable.LineProgressBar_rectfbarBottom,
                res.getDimension(R.dimen.px42));
        mRectfbarProgressWidth = mTypedArray.getDimension(R.styleable.LineProgressBar_rectfbarProgressWidth,
                res.getDimension(R.dimen.px800));
        mRectfbarProgressPointwidth = mTypedArray.getDimension(R.styleable.LineProgressBar_rectfbarProgressPointWidth,
                res.getDimension(R.dimen.px78));
        mRoundCornerRadius = mTypedArray.getDimension(R.styleable.LineProgressBar_roundCornerRadius, 2);

        mTypedArray.recycle();
        handler.sendEmptyMessageDelayed(REFRESH_POINT_PIC, 1000);
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);

        paint.setColor(roundColor); //设置圆环的颜色
        paint.setStyle(Paint.Style.FILL); //设置空心
        paint.setStrokeWidth(roundWidth);
        paint.setAntiAlias(true); //消除锯齿
        RectF barRectF = new RectF(mRectfbarLeft, mRectfbarTop, mRectfbarRight, mRectfbarBottom);
        canvas.drawRoundRect(barRectF, mRoundCornerRadius, mRoundCornerRadius, paint);
        paint.setColor(roundProgressColor); //设置进度的颜色
        /**用于定义的圆弧的形状和大小的界限*/
        RectF barProgress = new RectF(mRectfbarLeft, mRectfbarTop,
                mRectfbarProgressWidth * (float) progress / (float) max + mRectfbarLeft, mRectfbarBottom);
        canvas.drawRoundRect(barProgress, mRoundCornerRadius, mRoundCornerRadius, paint);
        RectF pointRectF = new RectF(barProgress.width(), 0, barProgress.width() + mRectfbarProgressPointwidth,
                mRectfbarProgressPointwidth);
        canvas.drawBitmap(point, null, pointRectF, null);
    }

    /**
     * 刷新搜台进度条上的点动画
     */
    private void refreshPointPicture()
    {
        if (picNum == pictures.length - 1)
        {
            picNum = 0;
        }
        else
        {
            picNum++;
        }

        point = pointBitmaps.get(picNum);
        postInvalidate();
        handler.sendEmptyMessageDelayed(REFRESH_POINT_PIC, 100);
    }

    /**
     * 清除搜台进度条上的点动画
     */
    public void clearPointPicture()
    {
        for (Bitmap btp : pointBitmaps)
        {
            if (!btp.isRecycled())
            {
                btp.recycle();
//                System.gc();
            }
        }
    }

    /**
     * 初始化搜台进度条上的点动画
     */
    private void initPointPicture()
    {
        pointBitmaps = new ArrayList<Bitmap>();
        for (int i = 0; i < pictures.length; i++)
        {
            Bitmap btp = getBitmap(pictures[i]);
            if (btp != null)
            {
                pointBitmaps.add(btp);
            }
        }
    }

    /**
     * 获取图片，对图片进行大小设置
     * @param resId 图片ID
     * @return Bitmap
     */
    private Bitmap getBitmap(int resId)
    {
        InputStream is = this.getResources().openRawResource(resId);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        options.inSampleSize = 1;
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inPreferredConfig = Config.RGB_565;
        Bitmap bitmap;

        try
        {
            bitmap = BitmapFactory.decodeStream(is, null, options);
            return bitmap;
        }
        catch (OutOfMemoryError e)
        {
            LogUtil.info(TAG, "getBitmap OutOfMemoryError");
        }
        return null;
    }

    /**
     * 停止刷新搜台进度条上的点动画
     */
    public void stopRefreshPointPic()
    {
        LogUtil.debug(TAG, "stopRefreshPointPic is in");
        handler.removeMessages(REFRESH_POINT_PIC);
    }

    /**
     * 获取进度.需要同步
     * @return int
     */
    public synchronized int getProgress()
    {
        return progress;
    }

    /**
     * 设置进度，此为线程安全控件，由于考虑多线的问题，需要同步 刷新界面调用postInvalidate()能在非UI线程刷新
     * @param progress 设置进度条的进度
     */
    public synchronized void setProgress(int progress)
    {
        if (progress < 0)
        {
            throw new IllegalArgumentException("progress not less than 0");
        }
        if (progress > max)
        {
            this.progress = max;
        }
        if (progress <= max)
        {
            this.progress = progress;
            postInvalidate();
        }

    }

    @Override
    public boolean handleMessage(Message msg)
    {
        switch (msg.what)
        {
            case REFRESH_POINT_PIC:
                refreshPointPicture();
                break;
            default:
                break;
        }
        return false;
    }
}
